package MTClient;

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

import MTRequest.MTRequestDataSource;

public class Client extends Panel implements Runnable, MTRequestDataSource, ActionListener
{
	// Components for the visual display of the chat windows
	private TextField tf = new TextField();
	private TextArea ta = new TextArea();
	// The socket connecting us to the server
	private Socket socket;
	
	private MessageCentre aMSGCenter;

	// Constructor
	public Client( String host, int port ) 
	{
		// Set up the screen
		setLayout( new BorderLayout() );
		add( "North", tf );
		add( "Center", ta );
		// We want to receive messages when someone types a line
		// and hits return, using an anonymous class as
		// a callback
		tf.addActionListener( this );
		// Connect to the server
		try {
			// Initiate the connection
			socket = new Socket( InetAddress.getLocalHost(), port );
			// We got a connection! Tell the world
			System.out.println( "connected to "+socket );
			// Let's grab the streams and create DataInput/Output streams
			// from them

			// Start a background thread for receiving messages
			
			aMSGCenter = new MessageCentre( 
					new DataInputStream( socket.getInputStream() ),
					new DataOutputStream( socket.getOutputStream() ) );
			
			new Thread( this ).start();
		} 
		catch( IOException ie ){ 
			System.out.println( ie ); 
		}
	}
	
	// Background thread runs this: show messages from other window
	public void run() 
	{
		try {
			// Receive messages
			aMSGCenter.ReceiveMSG();
		} 
		catch( IOException ie ){ 
			System.out.println( ie ); 
		}
	}
	
	public String GetRawData()
	{
		return "";
	}
	
	public void Notify( boolean aChanged )
	{
		System.out.println("----> void Notify( boolean aChanged )");
		System.out.println("aChanged:" + aChanged );
		System.out.println("<---- void Notify( boolean aChanged )");
	}
	
	public void actionPerformed( ActionEvent e ) {
		
		if( e.getActionCommand().matches( "1" )){
			aMSGCenter.SendRequest(MTConstant.MT_REQID_REIGSTER, this);
		}
		else if( e.getActionCommand().matches( "2" ) ){
			aMSGCenter.SendRequest(MTConstant.MT_REQID_SYNCHRONIZE_CONTACT_LIST, this);
		}
		else if( e.getActionCommand().matches( "3" ) ){
			aMSGCenter.SendRequest(MTConstant.MT_REQID_CREATE_EVENT, this);
		}
		else if( e.getActionCommand().matches( "4" ) ){
			aMSGCenter.SendRequest(MTConstant.MT_REQID_SYNCHRONIZE_DATA_FROM_LOCAL_DB, this);
		}
		else if( e.getActionCommand().matches( "5" ) ){
			aMSGCenter.SendRequest(MTConstant.MT_REQID_SYNCHRONIZE_DATA_FROM_SERVER, this);
		}
	}
}
